//公共数据
import config from './config'
import { ElMessage } from 'element-plus'
import manytomanyarrdata from './formConfig'
import { Session } from '@/utils/storage'
import api from '@/api'

//日期格式化
function formatDate(date, fmt){
    if (!date) {
        fmt = ""
        return fmt
    }
    date = new Date(date)
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
            RegExp.$1,
            (date.getFullYear() + "").substr(4 - RegExp.$1.length)
        )
    }
    let o = {
        "M+": date.getMonth() + 1,
        "d+": date.getDate(),
        "h+": date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, //小时
        "H+": date.getHours(), //小时
        "m+": date.getMinutes(),
        "s+": date.getSeconds()
    }
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + "";
            fmt = fmt.replace(
                RegExp.$1,
                RegExp.$1.length === 1 ? str : padLeftZero(str)
            )
        }
    }
    return fmt
}

//补零
function padLeftZero(str) {
    return ("00" + str).substr(str.length)
}

//数组取某个字段变成字符串叠加显示
function reverarr(arr, param) {
    let selectcode = ""
    if (!arr || !arr.length) {
        return ''
    }
    if (typeof arr === 'object') {
        for (var i = 0; i < arr.length; i++) {
            let ccc = i == (arr.length) - 1 ? "" : ",";
            selectcode += arr[i][param] + ccc;
        }
        return selectcode
    }
    return selectcode
}

function matchOption(Option, key, name) {
    let label = ""
    let color = ''
    for (let index = 0; index < Option.length; index++) {
        const element = Option[index]
        if (key == element.value) {
            label = element.label
            color = element.color || ''
        }
    }
    return name ? color : label
}

//判断数组是否可用
function ifvalidArr(arr) {
    return Object.prototype.toString.call(arr) === "[object Array]"
}

//判断数组是数组且不为空
function ifrrandnotnone(arr) {
    return Object.prototype.toString.call(arr) === "[object Array]" && arr.length > 0
}

function departroleformat(arr) {
    let rolename = ""
    if (ifvalidArr(arr)) {
        for (let index = 0; index < arr.length; index++) {
            const element = arr[index]
            rolename += element.department_role + '-' + element.role_name + (index == (arr.length - 1) ? '' : ',')
        }
    }
    return rolename
}

//处理tree数据
function transDatatotree(a, idStr, pidStr, chindrenStr) {
    const r = []
    const hash = {}
    const id = idStr
    const pid = pidStr
    const children = chindrenStr
    let i = 0
    let j = 0
    const len = a.length
    for (; i < len; i++) {
        hash[a[i][id]] = a[i]
    }
    for (; j < len; j++) {
        const aVal = a[j]
        const hashVP = hash[aVal[pid]]
        if (hashVP) {
            !hashVP[children] && (hashVP[children] = [])
            hashVP[children].push(aVal)
        } else {
            r.push(aVal)
        }
    }
    return r
}

//文件格式转化
function varfile(url) {
    if (!url) {
        return ''
    }
    let vnskja = url.slice(url.lastIndexOf("/") + 1, url.length)
    return decodeURIComponent(vnskja)
}

/* 
  获取级联选择器的值
  value   --最后一级的值
  option  --级联数组
   */
function getCascaderFullValue(value, option, key) {
    let optionFullValue = []
    _getParentId(optionFullValue, option, option, value)
    if (key == "label") {
        return optionFullValue.join('/')
    } else {
        return optionFullValue
    }
    function _getParentId(optionFullValue, option, _option, _value) {
        if (!Array.isArray(option)) return

        let indexk = option.findIndex(item => item.value === _value)
        if (indexk >= 0) {
            optionFullValue.push(option[indexk][key])
            return
        }
        for (let optionItem of option) {
            if (Array.isArray(optionItem.children)) {
                let index = optionItem.children.findIndex(item => item.value === _value)
                if (index >= 0) {
                    optionFullValue.push(optionItem[key])
                    optionFullValue.push(optionItem.children[index][key])
                    if (_option.findIndex(item => item.value === optionItem.value) < 0) //is original item
                        _getParentId(optionFullValue, _option, _option, optionItem.value)
                } else {
                    _getParentId(optionFullValue, optionItem.children, _option, _value)
                }
            }
        }
    }
}

//过滤搜索栏参数
function formatSearchParams(searchList, params) {
    let obj = {}
    for (let i = 0; i < searchList.length; i++) {
        let item = searchList[i]
        //有值才格式化
        if (params[item.key]) {
            if (['input', 'select'].includes(item.searchtype)) {
                //输入框 下拉框
                obj[item.key] = params[item.key]
            } else if (item.searchtype == 'time') {
                //时间
                obj[item.key] = commonV.formatDate(params[item.key], 'yyyy-MM-dd')
            } else if (item.searchtype == 'timeQuantum') {
                //时间段
                let start_time = commonV.formatDate(params[item.key][0], 'yyyy-MM-dd')
                let end_time = commonV.formatDate(params[item.key][1], 'yyyy-MM-dd')
                obj[item.key] = JSON.stringify([start_time, end_time])
            } else if (item.searchtype == 'Cascader') {
                //级联选择器
                params[item.key] = params[item.key][params[item.key].length - 1]
            }
        }
    }
    return obj
}

//id数组
function idtoarrry(arr, idname = 'id') {
    if (ifvalidArr(arr)) {
        let arrK = JSON.parse(JSON.stringify(arr))
        let array = []
        for (var i = 0; i < arrK.length; i++) {
            let param = (idname == 'id' ? parseInt(arrK[i][idname]) : arrK[i][idname])
            array.push(param)
        }
        return array
    }
    return []
}

//导出
function exportDataList(multipleSelection, filename, url, ontherparams) {
    return new Promise(resolve => {
        let params = {}
        params = ontherparams
        if (multipleSelection.length > 0) {
            params.ids = JSON.stringify(idtoarrry(multipleSelection))
        }
        api.exportaxiosdata(url, params).then((res) => {
            const blob = new Blob([res], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
            });
            const downloadElement = document.createElement("a")
            const href = window.URL.createObjectURL(blob)
            downloadElement.href = href
            downloadElement.download = filename
            document.body.appendChild(downloadElement)
            downloadElement.click()
            document.body.removeChild(downloadElement) // 下载完成移除元素
            window.URL.revokeObjectURL(href) // 释放掉blob对象
            resolve(res)
        }).catch(err => {
            resolve(null)
            ElMessage.error(`后台接口${api}报错，请联系开发人员`)
        })
    })
}

//require方法
function require(imgPath) {
    try {
        const handlePath = imgPath.replace('@', '..')
        // https://vitejs.cn/guide/assets.html#the-public-directory
        return new URL(handlePath, import.meta.url).href
    } catch (error) {
        console.warn(error)
    }
}

//提取数组id转化为字符串
function deveridarrry(arr) {
    if (arr) {
        let array = []
        for (var i = 0; i < arr.length; i++) {
            array.push(parseInt(arr[i].id))
        }
        return JSON.stringify(array)
    }
    return ''
}

//列表参数
function getwt_mesageValue(wt_mesage, ruleForm) {
    const params = new FormData()
    //获取弹窗类型
    let manytomanyArr = []
    if (ifrrandnotnone(manytomanyarrdata)) {
        manytomanyarrdata.forEach(element => {
            manytomanyArr.push(element?.paramtype)
        })
    }
    //获取弹窗类型
    for (let index = 0; index < wt_mesage.length; index++) {
        let key = wt_mesage[index].prop
        let paramtype = wt_mesage[index].paramtype
        if (key && typeof ruleForm[key] != "undefined" && ruleForm[key] != null && wt_mesage[index].ifupload !== false) {
            if (paramtype == "select" && wt_mesage[index].multiple) {
                //下拉多选
                params.append(key, JSON.stringify(ruleForm[key]))
            } else if (paramtype == 'time' || paramtype == 'start_end_daterange') {
                //日期时间
                if (wt_mesage[index].datetype) {
                    params.append(key, formatDate(ruleForm[key], 'yyyy-MM-dd HH:mm:ss'))
                } else if (wt_mesage[index].timetype) {
                    params.append(key, formatDate(ruleForm[key], 'yyyy-MM-dd HH:mm:ss'))
                } else {
                    params.append(key, formatDate(ruleForm[key], 'yyyy-MM-dd HH:mm:ss'))
                }
            } else if (paramtype == 'upload') {
                /*附件*/
                let exisfile = []
                for (let index = 0; index < ruleForm[key].length; index++) {
                    if (typeof ruleForm[key][index].raw == "undefined") {
                        //已存在文件
                        exisfile.push(ruleForm[key][index])
                    } else {
                        //新增文件
                        params.append(key + "_files", ruleForm[key][index].raw)
                    }
                }
                params.append(key, JSON.stringify(exisfile))
                /*附件*/
            } else if (
                manytomanyArr.some(itk => itk == paramtype)
            ) {
                if (wt_mesage[index].prop == 'role_ids') {
                    //新增用户
                    if (ruleForm[key].length > 0) {
                        let roleIds = JSON.parse(deveridarrry(ruleForm[key]))
                        params.append(key, roleIds.join(','))
                    } else {
                        params.append(key, '')
                    }
                } else {
                    //manytomanyArr里面类型
                    if (ruleForm[key].length > 0) {
                        params.append(key, deveridarrry(ruleForm[key]))
                    } else {
                        params.append(key, '')
                    }
                }
            } else if (paramtype == 'keyinobject' || paramtype == 'objectinkey') {
                params.append(key, ruleForm[key].id)
            } else if (['imgupload'].includes(paramtype)) {
                //图片
                let pictures = []
                for (let index = 0; index < ruleForm[key].length; index++) {
                    const element = ruleForm[key][index]
                    if (typeof element.raw == "undefined") {
                        pictures.push(element)
                    } else {
                        //"imgs"
                        params.append(key + "_files", ruleForm[key][index].raw)
                    }
                }
                params.append(key, JSON.stringify(pictures))
            } else if (paramtype == 'cascader' && ifrrandnotnone(ruleForm[key])) {
                params.append(key, ruleForm[key][ruleForm[key].length - 1])
            } else {
                params.append(key, ruleForm[key])
            }
        }
    }
    return params
}

//生成编号
async function creatnewcode(type) {
    let codeObj = await api.changeaxiosdata("noSeq", "post", { 'table_type': type })
    return codeObj.msg
}

async function getcurrenUserPermissionasync(path, type = 2) {
    let comdata = ""
    if (type == 1) {
        //列表页直接通过路由获取权限
        let arrA = path.split("/")
        let flag = 0
        for (let index = 0; index < arrA.length; index++) {
            if (arrA[index]) {
                comdata = comdata + (comdata != '' ? "&&" : '') + arrA[index]
                flag++
                if (flag == 2) {
                    break
                }
            }
        }
        comdata = comdata + "||"
    } else {
        //不通过路由自定义命名
        comdata = path
    }
    let params = {}
    params.id = Session.get('UserMsg').id
    let res = await api.getaxiosdata("users", params)
    if (res) {
        return changepermission(comdata, res.results[0])
    }
    return []
}

//获取当前用户权限
function changepermission(comdata, row) {
    let permission = [];
    //新增个人权限
    permission = row.permission_type ? row.personal_permission.split(",") : row.permission.split(",");
    for (let index = permission.length - 1; index >= 0; index--) {
        const element = permission[index];
        if (element.indexOf(comdata) == -1) {
            permission.splice(index, 1);
        } else {
            permission[index] = permission[index].replace(comdata, "");
        }
    }
    return permission;
}

//处理节点中有hidden
function filterTreeArray(tree, limit) {
    return tree.filter((item) => {
        if (limit) {
            return limit.includes(item.meta?.key)
        }
        return !item.meta?.isHide;
    }).map((item) => {
        item = Object.assign({}, item)
        if (item.children) {
            item.children = filterTreeArray(item.children, limit);
        }
        return item;
    });
}

export default {
    formatDate,
    reverarr,
    matchOption,
    departroleformat,
    transDatatotree,
    varfile,
    ifrrandnotnone,
    getCascaderFullValue,
    formatSearchParams,
    idtoarrry,
    ifvalidArr,
    exportDataList,
    require,
    deveridarrry,
    getwt_mesageValue,
    creatnewcode,
    getcurrenUserPermissionasync,
    filterTreeArray,
    statusOption: config.statusOption,
    chooseComponent: config.chooseComponent
}